<?php
/**
 * 
 *
 * @file UserController.clas.php
 * @auther liyangguang
 * @date 2011-12-08
 */
require_once(FITWOW_ROOT_PATH . 'languages/en_us/user.php');
require_once(FITWOW_ROOT_PATH . 'apps/common/Utils.class.php');
require_once(FITWOW_ROOT_PATH . 'apps/common/Image.class.php');

class UserController extends Zend_Controller_Action
{
    const THUMB_WIDTH  = 150;
    const THUMB_HEIGHT = 150;
    const THUMB_DEFAULT_PATH = 'image/face.png';
    const BID_PAGE_SIZE = 5;
    const GOAL_PAGE_SIZE = 5;
    const REVIEW_PAGE_SIZE = 5;
    
    const FB_PIC_URL = 'http://graph.facebook.com/{*$uid*}/picture?type=large';
    
    public function init()
    {
        $this->_tplvar['web_site'] = FITWOW_WEB_SITE;
        
        //TODO:::
      
        if (isset($_SESSION['user'])) {
            $objUsersTable = new UsersTable();        
            $this->_tplvar['user'] = $objUsersTable->findUserWithID($_SESSION['user']['id'])->toArray();
            $this->_tplvar['user_firstname'] = $this->_tplvar['user']['firstname'];
            $this->_tplvar['user_type'] = $this->_tplvar['user']['user_type'];
        }
        $objGoalTypesTable = new GoalTypesTable();
        $objAgeTypesTable  = new AgeTypesTable();
        $objBodyTypesTable = new BodyTypesTable();
        $objTrainerTypesTable = new TrainerTypesTable();
        $objSessionTypesTable = new SessionTypesTable();
        $objAreaTypesTable = new AreaTypesTable();
        $objGenderTypesTable = new GenderTypesTable();
        $this->_tplvar['gender_list'] = $objGenderTypesTable->fetchAll()->toArray();
        $this->_tplvar['gen_goal_list'] = $objGoalTypesTable->fetchAll()->toArray();
        $this->_tplvar['age_list']      = $objAgeTypesTable->fetchAll()->toArray();
        $this->_tplvar['body_list']     = $objBodyTypesTable->fetchAll()->toArray();
        $this->_tplvar['area_list']     = $objAreaTypesTable->fetchAll()->toArray();
        $this->_tplvar['trainer_type_list'] = $objTrainerTypesTable->fetchAll()->toArray();
        $this->_tplvar['session_list'] = $objSessionTypesTable->fetchAll()->toArray();
        //configure
        $this->_tplvar['objConfigModel'] = new ConfigModel();
    }
    
    public function accountAction()
    {        
        //TODO:check user login
        $this->_checkUserLogin();
        $this->_tplvar['title'] = 'Account Setting';
        $this->_tplvar['no_login_pop'] = true;
        $GLOBALS['g_smarty']->display_tpl('account.tpl', $this->_tplvar);
    }
    
    public function basicAction()
    {
        //TODO: check user login
        $this->_checkUserLogin();
        $objGenderTypesTable = new GenderTypesTable();
        $objAreaTypesTable   = new AreaTypesTable();
        $this->_tplvar['title'] = 'Basic profile';
        $this->_tplvar['gender_list'] = $objGenderTypesTable->fetchAll()->toArray();
        $this->_tplvar['area_list']   = $objAreaTypesTable->fetchAll()->toArray();
        

        $this->_tplvar['no_login_pop'] = true;
        $GLOBALS['g_smarty']->display_tpl('basic_profile.tpl', $this->_tplvar);
    }
    
    public function clientprofileAction()
    {
        //TODO: check user login
        $this->_checkUserLogin();
        $this->_tplvar['title'] = 'Client training profile';
        $objClientGenGoalTypesTable = new ClientGenGoalTypesTable();
        $objAgeTypesTable  = new AgeTypesTable();
        $objBodyTypesTable = new BodyTypesTable();
        $this->_tplvar['gen_goal_list'] = $objClientGenGoalTypesTable->fetchAll()->toArray();
        $this->_tplvar['age_list']      = $objAgeTypesTable->fetchAll()->toArray();
        $this->_tplvar['body_list']     = $objBodyTypesTable->fetchAll()->toArray();
        $arrSelectedGenGoals = explode('#', trim($this->_tplvar['user']['gen_goals'], "#"));
        
        foreach ($this->_tplvar['gen_goal_list'] as &$gen_goal) {
            if (in_array($gen_goal['id'] , $arrSelectedGenGoals)) {
                
                $gen_goal['selected'] = true;
            }
            else {
                $gen_goal['selected'] = false;
            }
        }
        $arrActivityList = explode('#', trim($this->_tplvar['user']['interested_activities']));
        $this->_tplvar['activity_list'] = array();
        foreach ($arrActivityList as $activity) {
            if (empty($activity))continue;
            $this->_tplvar['activity_list'][]['name'] = $activity;
        }
        //configure
        $this->_tplvar['no_login_pop'] = true;
        $GLOBALS['g_smarty']->display_tpl('client_training_profile.tpl', $this->_tplvar);
    }
    
    public function trainerprofileAction()
    {
        //TODO: check user login
        $this->_checkUserLogin();
        $objGoalTypesTable = new GoalTypesTable();
        $objAgeTypesTable  = new AgeTypesTable();
        $objBodyTypesTable = new BodyTypesTable();
        $objExperienceTypesTable = new ExperienceTypesTable();
        $objTrainingserviceTable = new TrainingserviceTypesTable();
        $objCredentialTypesTable = new CredentialTypesTable();
        $objEdulevelTypesTable = new EdulevelTypesTable();
        $this->_tplvar['credential_list'] = $objCredentialTypesTable->fetchAll()->toArray();
        $this->_tplvar['age_list']      = $objAgeTypesTable->fetchAll()->toArray();
        $this->_tplvar['body_list']     = $objBodyTypesTable->fetchAll()->toArray();
        $this->_tplvar['experience_list'] = $objExperienceTypesTable->fetchAll()->toArray();
        $this->_tplvar['trainingservice_list'] = $objTrainingserviceTable->fetchAll()->toArray();
        $this->_tplvar['edulevel_list'] = $objEdulevelTypesTable->fetchAll()->toArray();
        $arrSelectedCredentials = explode('#', trim($this->_tplvar['user']['credentials'], "#"));
        
        foreach ($this->_tplvar['credential_list'] as &$credential) {
            if (in_array($credential['id'] , $arrSelectedCredentials)) {
                
                $credential['selected'] = true;
            }
            else {
                $credential['selected'] = false;
            }
        }
        $arrActivityList = explode('#', trim($this->_tplvar['user']['interested_activities']));
        $this->_tplvar['activity_list'] = array();
        foreach ($arrActivityList as $activity) {
            if (empty($activity))continue;
            $this->_tplvar['activity_list'][]['name'] = $activity;
        }
        $this->_tplvar['no_login_pop'] = true;
        $this->_tplvar['title'] = 'Trainer profile';
        $GLOBALS['g_smarty']->display_tpl('trainer_profile.tpl', $this->_tplvar);
        
    }
    
    public function transactionAction()
    {
        //TODO: check user login
        $this->_checkUserLogin();
        $this->_tplvar['title'] = 'Transtions history';
        $objGoalsTable = new GoalsTable();
        $this->_tplvar['goal_list'] = $objGoalsTable->getProjectListWithUID($this->_tplvar['user']['id'])->toArray();
        //configure
        $this->_tplvar['objConfigModel'] = new ConfigModel();
        $GLOBALS['g_smarty']->display_tpl('transactions_history.tpl', $this->_tplvar);
    }
    
    public function dashboardAction()
    {
        $this->_checkUserLogin();
        $intUID = $_SESSION['user']['id'];
        if ($intUID <= 0) {
            $response = $this->getResponse();
            $response->setRedirect('/user/login');
            return;
        }
        $objUserModel = new UserModel();
        $row = $objUserModel->getUserInfo($intUID);

        $this->_tplvar['user'] = $row;
        $objGoalsTable = new GoalsTable();
        $arrWhere = array(
            'uid='.$this->_tplvar['user']['id'],
        );
        $arrOrder = array(
            'id DESC',
        );
        $this->_tplvar['goal_list'] = $objGoalsTable->getProjectListByOffset($arrWhere, $arrOrder, 0, UserController::GOAL_PAGE_SIZE);
        
        $this->_tplvar['title'] = 'user dashboard';
        $objGoalModel = new GoalModel();
        $objUsersTable = new UsersTable();
        $this->_tplvar['friends_goal_list'] = $objGoalsTable->getFriendsGoalListWithUID($this->_tplvar['user']['id'], 0, UserController::GOAL_PAGE_SIZE);
        foreach ($this->_tplvar['friends_goal_list'] as &$goal) {
            $goal['user'] = $objUsersTable->findUserWithID($goal['uid']);
            
        }
        //generate the page list
        $this->_genMyGoalsAndFriendGoalsPageList();
        
        
        if ($this->_tplvar['user']['user_type'] == 1) {
            
            $this->_tplvar['review_list'] = $objGoalModel->getReviewListWithUID($this->_tplvar['user']['id'], 0, UserController::REVIEW_PAGE_SIZE);
            
            $this->_tplvar['bid_list'] = $objGoalModel->getBidListWithUID($this->_tplvar['user']['id'], 0, UserController::BID_PAGE_SIZE);
            
            $this->_genRevewAndBidPageList();
        }
        else {
            //TODO
        }
        $objFriendsTable = new FriendsTable();
        $this->_tplvar['friend_list'] = $objFriendsTable->getMyFriendListWithUID($this->_tplvar['user']['id']);
        //facebook invite friends
        if (empty($this->_tplvar['user']['fb_uid'])) {
            //not facebook user
            $this->_tplvar['user']['facebook_user'] = 0;
        }
        else {
            $this->_tplvar['user']['facebook_user'] = 1;
            if (empty($this->_tplvar['user']['fb_json_friends'])) {
                $this->_tplvar['user']['upload_fb_friends'] = 0;
                
            }
            else {
                $arrFbFriendList= json_decode($this->_tplvar['user']['fb_json_friends']);
                $arrNotInvitedFbFriendList = array();
                $this->_tplvar['user']['fb_friend_list'] = array();
                foreach ($arrFbFriendList as $friend) {
                    if ($friend->is_invited == 0) {
                        $arrNotInvitedFbFriendList[] = array('name'=> $friend->name, 'id'=>$friend->id);
                    }
                }
                $intCnt = 3;
                if (count($arrNotInvitedFbFriendList) < $intCnt) {
                    $intCnt = count($arrNotInvitedFbFriendList);
                }
                $arrRandKeys = array_rand($arrNotInvitedFbFriendList, $intCnt);
                if (!empty($arrRandKeys)) {
                    foreach ($arrRandKeys as $key) {
                        
                        $this->_tplvar['user']['fb_friend_list'][] = $arrNotInvitedFbFriendList[$key];
                    }
                }
                $this->_tplvar['user']['upload_fb_friends'] = 1;
            }
        }
        //TODO: alerts and ranks
        $objNoticeModel = new NoticeModel();
        $this->_tplvar['alert_list'] = $objNoticeModel->getNoReadNoticeListWithUID($this->_tplvar['user']['id']);
        //profile complete
        $this->_tplvar['profile_complete'] = $this->_calcProfileComplete($this->_tplvar['user']['id']);
        if ($this->_tplvar['user']['facebook_user']) {
            $this->_tplvar['no_login_pop'] = true;
        }
        $GLOBALS['g_smarty']->display_tpl('user_dashboard.tpl', $this->_tplvar);
    }
    
    public function bidsAction()
    {
        $this->_checkUserLogin();
        $intUID = $_SESSION['user']['id'];
        if ($intUID <= 0) {
            $response = $this->getResponse();
            $response->setRedirect('/user/login');
            return;
        }
        if ($this->_tplvar['user']['user_type'] == 2) {
            $response = $this->getResponse();
            $response->setRedirect('/user/goals');
            return;
        }
        $objUserModel = new UserModel();
        $row = $objUserModel->getUserInfo($intUID);

        $this->_tplvar['user'] = $row;
        
        $arrWhere = array(
            'uid='.$this->_tplvar['user']['id'],
        );
        $arrOrder = array(
            'id DESC',
        );
        $objGoalsTable = new GoalsTable();
        $this->_tplvar['goal_list'] = $objGoalsTable->getProjectListByOffset($arrWhere, $arrOrder, 0, UserController::GOAL_PAGE_SIZE)->toArray();
        $this->_tplvar['friends_goal_list'] = $objGoalsTable->getFriendsGoalListWithUID($this->_tplvar['user']['id'], 0, UserController::GOAL_PAGE_SIZE);
        $objUsersTable = new UsersTable();
        foreach ($this->_tplvar['friends_goal_list'] as &$goal) {
            $goal['user'] = $objUsersTable->findUserWithID($goal['uid']);
            
        }
        //generate the page list
        $this->_genMyGoalsAndFriendGoalsPageList();
        
        
        
        $this->_tplvar['title'] = 'my bids';
        
        $objGoalModel = new GoalModel();
        
        $this->_tplvar['review_list'] = $objGoalModel->getReviewListWithUID($this->_tplvar['user']['id'], 0, UserController::REVIEW_PAGE_SIZE);
        
        $this->_tplvar['bid_list'] = $objGoalModel->getBidListWithUID($this->_tplvar['user']['id'], 0, UserController::BID_PAGE_SIZE);
        $this->_genRevewAndBidPageList();
        //TODO: alerts and ranks
        $objFriendsTable = new FriendsTable();
        $this->_tplvar['friend_list'] = $objFriendsTable->getMyFriendListWithUID($this->_tplvar['user']['id'], 0, 10);
        $this->_tplvar['no_more'] = true;
        
        //profile complete
        $this->_tplvar['profile_complete'] = $this->_calcProfileComplete($this->_tplvar['user']['id']);
        
        $this->_tplvar['no_login_pop'] = true;
        $GLOBALS['g_smarty']->display_tpl('user_bids.tpl', $this->_tplvar);
    }
    
    public function goalsAction()
    {
        $this->_checkUserLogin();
        $intUID = $_SESSION['user']['id'];
        if ($intUID <= 0) {
            $response = $this->getResponse();
            $response->setRedirect('/user/login');
            return;
        }
        if ($this->_tplvar['user']['user_type'] == 1) {
            $response = $this->getResponse();
            $response->setRedirect('/user/bids');
            return;
        }
        $objUserModel = new UserModel();
        $row = $objUserModel->getUserInfo($intUID);

        $this->_tplvar['user'] = $row;
        $objGoalsTable = new GoalsTable();
        $arrWhere = array(
            'uid='.$this->_tplvar['user']['id'],
        );
        $arrOrder = array(
            'id DESC',
        );
        $this->_tplvar['goal_list'] = $objGoalsTable->getProjectListByOffset($arrWhere, $arrOrder, 0, UserController::GOAL_PAGE_SIZE)->toArray();
        $this->_tplvar['friends_goal_list'] = $objGoalsTable->getFriendsGoalListWithUID($this->_tplvar['user']['id'], 0, UserController::GOAL_PAGE_SIZE);
        $objUsersTable = new UsersTable();
        foreach ($this->_tplvar['friends_goal_list'] as &$goal) {
            $goal['user'] = $objUsersTable->findUserWithID($goal['uid']);
            
        }
        $this->_genMyGoalsAndFriendGoalsPageList();

        $this->_tplvar['title'] = 'my goals';
        //TODO: alerts and ranks
        $objFriendsTable = new FriendsTable();
        $this->_tplvar['friend_list'] = $objFriendsTable->getMyFriendListWithUID($this->_tplvar['user']['id'], 0, 10);
        
        $this->_tplvar['no_more'] = true;
        
        //profile complete
        $this->_tplvar['profile_complete'] = $this->_calcProfileComplete($this->_tplvar['user']['id']);
        
        $this->_tplvar['no_login_pop'] = true;
        $GLOBALS['g_smarty']->display_tpl('user_goals.tpl', $this->_tplvar);
    }
    
    public function loginAction()
    {
        $this->_tplvar['title'] = 'User Login';
        
        $objAreaTypesTable   = new AreaTypesTable();
        $this->_tplvar['area_list']   = $objAreaTypesTable->fetchAll()->toArray();
        if (isset($_SESSION['goal'])) {
            if ($_SESSION['goal']['gen_goal_id'] > 0) {
                $this->_tplvar['goal_name'] = $this->_tplvar['objConfigModel']->getGenGoal($_SESSION['goal']['gen_goal_id']);
            }
            else {
                $this->_tplvar['goal_name'] = $_SESSION['goal']['goal_name'];
            }
        }
        $strJoinUrl  = $this->_tplvar['web_site'].'/user/join';
        if (isset($_SERVER['HTTP_REFERER'])) {
            $strPreUrl = trim($_SERVER['HTTP_REFERER'], '/');
        }
        if (isset($strPreUrl) && strncasecmp($strPreUrl, $this->_tplvar['web_site'], strlen($this->_tplvar['web_site'])) !== 0 && strncasecmp($strPreUrl, $strJoinUrl, strlen($strJoinUrl)) !== 0){
            $_SESSION['pre_url'] = $strPreUrl;
        }
        

        $this->_tplvar['no_login_pop'] = true;
        $GLOBALS['g_smarty']->display_tpl('login.tpl', $this->_tplvar);
    }
    
    public function joinAction()
    {
        $this->_tplvar['title'] = 'User Join';
        if (isset($_SESSION['goal'])) {
            if ($_SESSION['goal']['gen_goal_id'] > 0) {
                $this->_tplvar['goal_name'] = $this->_tplvar['objConfigModel']->getGenGoal($_SESSION['goal']['gen_goal_id']);
            }
            else {
                $this->_tplvar['goal_name'] = $_SESSION['goal']['goal_name'];
            }
        }

        $objAreaTypesTable   = new AreaTypesTable();
        $objGenderTypesTable = new GenderTypesTable();
        $this->_tplvar['gender_list'] = $objGenderTypesTable->fetchAll()->toArray();
        $this->_tplvar['area_list']   = $objAreaTypesTable->fetchAll()->toArray();
        
        $GLOBALS['g_smarty']->display_tpl('join.tpl', $this->_tplvar);
        $this->_tplvar['no_login_pop'] = true;
    }
    
    public function joinorloginAction()
    {
        //var_dump($_SERVER['HTTP_REFERER']);
        $this->_tplvar['title'] = 'User Join';
        $this->_tplvar['ggid'] = intval($this->_request->getParam('ggid'));
        if ($this->_tplvar['ggid'] > 0) {
            $this->_tplvar['goal_name'] = $this->_tplvar['objConfigModel']->getGenGoal($this->_tplvar['ggid']);
        }
        $objAreaTypesTable   = new AreaTypesTable();
        $this->_tplvar['area_list']   = $objAreaTypesTable->fetchAll()->toArray();
        
        $this->_tplvar['no_login_pop'] = true;
        $GLOBALS['g_smarty']->display_tpl('joinorlogin.tpl', $this->_tplvar);
        
    }
    
    public function detailAction()
    {
        $intUID = intval($this->_request->getParam('uid'));
        if ($intUID <= 0) {
            $response = $this->getResponse();
            $response->setRedirect('/index/notfound');
            
            return;
        }
        
        $objUserModel = new UserModel();
        $objGoalModel = new GoalModel();
        $row = $objUserModel->getUserInfo($intUID);
        if ($row === false) {
            $response = $this->getResponse();
            $response->setRedirect('/index/notfound');
            return;
        }
        $arrWhere = array(
            'uid='.$row['id'],
        );
        $arrOrder = array(
            'id DESC',
        );
        $this->_tplvar['user'] = $row;
        $objGoalsTable = new GoalsTable();
        $this->_tplvar['goal_list'] = $objGoalsTable->getProjectListByOffset($arrWhere, $arrOrder, 0, UserController::GOAL_PAGE_SIZE)->toArray();
        //$this->_tplvar['gfoal_']
        $this->_tplvar['objConfigModel'] = new ConfigModel();
        $this->_tplvar['title'] = 'user account profile';
        $this->_tplvar['friends_goal_list'] = $objGoalsTable->getFriendsGoalListWithUID($this->_tplvar['user']['id'], 0, UserController::GOAL_PAGE_SIZE);
        $objUsersTable = new UsersTable();
        foreach ($this->_tplvar['friends_goal_list'] as &$goal) {
            $goal['user'] = $objUsersTable->findUserWithID($goal['uid']);
            
        }
        //generate the page list
        $this->_genMyGoalsAndFriendGoalsPageList();
        if ($this->_tplvar['user']['user_type'] == 1) {
            
            $this->_tplvar['review_list'] = $objGoalModel->getReviewListWithUID($this->_tplvar['user']['id'], 0, UserController::REVIEW_PAGE_SIZE);
            $this->_tplvar['bid_list'] = $objGoalModel->getBidListWithUID($this->_tplvar['user']['id'], 0, UserController::BID_PAGE_SIZE);
            $this->_genRevewAndBidPageList();
        }
        $this->_tplvar['no_more'] = true;
        if (isset($_SESSION['user']) && $_SESSION['user']['id'] == $this->_tplvar['user']['id']) {
            //profile complete
            $this->_tplvar['profile_complete'] = $this->_calcProfileComplete($this->_tplvar['user']['id']);
        }
        $GLOBALS['g_smarty']->display_tpl('user_detail.tpl', $this->_tplvar);
    }
    
        
    public function rankingAction()
    {
        $objUsersTable = new UsersTable();
        $this->_tplvar['user_list'] = $objUsersTable->getUserList();
        $this->_tplvar['trainer_list'] = $objUsersTable->getTrainerList();
        if (isset($_SESSION['user'])) {
            $this->_tplvar['user']['rank'] = $objUsersTable->getUserRank($this->_tplvar['user']['rank_points']);
        }
        $this->_tplvar['title'] = 'User ranking';
        $GLOBALS['g_smarty']->display_tpl('user_ranking.tpl', $this->_tplvar);
    }
    
    public function findallAction()
    {
        $objUsersTable = new UsersTable();
        $this->_tplvar['user_list'] = $objUsersTable->getUserList();
        if (isset($_SESSION['user'])) {
            $this->_tplvar['user']['rank'] = $objUsersTable->getUserRank($this->_tplvar['user']['rank_points']);
        }
        $this->_tplvar['title'] = 'Find all';
        $this->_tplvar['find_all'] = true;
        $GLOBALS['g_smarty']->display_tpl('people_like_me.tpl', $this->_tplvar);
    }
    
    public function peoplelikemeAction()
    {
        $this->_checkUserLogin();
        $objUsersTable = new UsersTable();
        $this->_tplvar['user_list'] = $objUsersTable->getUserListLikeMe($this->_tplvar['user']);
        if (isset($_SESSION['user'])) {
            $this->_tplvar['user']['rank'] = $objUsersTable->getUserRank($this->_tplvar['user']['rank_points']);
        }
        $this->_tplvar['title'] = 'Find people like me';
        $GLOBALS['g_smarty']->display_tpl('people_like_me.tpl', $this->_tplvar);
    }
     
    
    /** -------------------后台的数据提交操作 ---------------------------*/
    public function readalertAction()
    {
        $this->_ajaxCheckLogin();
        $intNID = intval($this->_request->getParam('nid'));
        $objNoticeModel = new NoticeModel();
        $objNoticeModel->setNoticeRead($intNID);
        $arrResult = array('status' => 0, 'content' => 'success.');
        echo json_encode($arrResult);
        
    }
    //异步获取有关data的数据
    public function ajaxloaddataAction()
    {
        $act = $this->_request->getParam('act');
        $intUID = intval($this->_request->getParam('uid'));
        $intCurPage = intval($this->_request->getParam('page'));
        if ($intCurPage === 0) {
            $intCurPage = 1;
        }
        $intPageSize = 0;
        $arrResult = array('status' => 0);
        
        $objUsersTable = new UsersTable();   
        
        $this->_tplvar['user'] = $objUsersTable->findUserWithID($intUID)->toArray();
        
        switch($act) {
            case 'my_goal' : {
                $intOffset = ($intCurPage - 1) * UserController::GOAL_PAGE_SIZE;
                $objGoalsTable = new GoalsTable();
                $arrWhere = array(
                    'uid='.$this->_tplvar['user']['id'],
                );
                $arrOrder = array(
                    'id DESC',
                );
              
                $arrDataList = $objGoalsTable->getProjectListByOffset($arrWhere, $arrOrder, $intOffset, UserController::GOAL_PAGE_SIZE)->toArray();
                foreach ($arrDataList as &$data ) {
                    if ($data['gen_goal_id'] > 0) {
                        $data['goal_name'] = $this->_tplvar['objConfigModel']->getGenGoal($data['gen_goal_id']);
                        
                    }
                    $data['status'] = $this->_tplvar['objConfigModel']->getNextStep($data['status']);
                    $data['created_time'] = strftime('%m/%d/%Y', $data['created_time']);
                    
                }
                $intCnt = intval($objGoalsTable->getProjectCnt($arrWhere));
                $intPageSize = UserController::GOAL_PAGE_SIZE;
                break;
            }
            case 'friends_goal' : {
                $objUsersTable = new UsersTable();
                $objGoalsTable = new GoalsTable();
                $intOffset = ($intCurPage - 1) * UserController::GOAL_PAGE_SIZE;
                
                $arrDataList = $objGoalsTable->getFriendsGoalListWithUID($this->_tplvar['user']['id'], $intOffset, UserController::GOAL_PAGE_SIZE);
                foreach ($arrDataList as &$data ) {
                    if ($data['gen_goal_id'] > 0) {
                        $data['goal_name'] = $this->_tplvar['objConfigModel']->getGenGoal($data['gen_goal_id']);
                        
                    }
                    $data['status'] = $this->_tplvar['objConfigModel']->getSearchGoalStatus($data['status']);
                    $data['area'] = $this->_tplvar['objConfigModel']->getArea($data['area_id']);
                    $data['created_time'] = strftime('%b %d,%Y', $data['created_time']);
                    $data['deadline'] = strftime('%m/%d/%Y', $data['deadline']);
                    $data['budget'] = empty($data['budget']) ? 0 : $data['budget'];
                    $data['user'] = $objUsersTable->findUserWithID($data['uid'])->toArray();
                    $data['user']['firstname'] = $this->_tplvar['objConfigModel']->genUsername($data['user']['firstname'], $data['user']['lastname']);
                }
                $intCnt = $objGoalsTable->getFriendsGoalListCntWithUID($this->_tplvar['user']['id']);
                $intPageSize = UserController::GOAL_PAGE_SIZE;
                break;
            }
            case 'bid' : {
                $objGoalModel = new GoalModel();
                $objBidsTable = new BidsTable();
                $intOffset = ($intCurPage - 1) * UserController::BID_PAGE_SIZE;
                $arrDataList = $objGoalModel->getBidListWithUID($this->_tplvar['user']['id'], $intOffset, UserController::BID_PAGE_SIZE);
                foreach ($arrDataList as &$data) {
                    $data['created_time'] = strftime('%m/%d/%Y', $data['created_time']);
                    $data['status'] = $this->_tplvar['objConfigModel']->getStatus($data['goal']['status']);
                }
                $intCnt = intval($objBidsTable->getBidListCntWithUID($this->_tplvar['user']['id']));
                
                $intPageSize = UserController::BID_PAGE_SIZE;
                break;
            }
            case 'review' : {
                $objGoalModel = new GoalModel();
                $objReviewsTable = new ReviewsTable();
                $intOffset = ($intCurPage - 1) * UserController::REVIEW_PAGE_SIZE;
                $arrDataList = $objGoalModel->getReviewListWithUID($this->_tplvar['user']['id'], $intOffset, UserController::REVIEW_PAGE_SIZE);
                foreach ($arrDataList as &$data) {
                    $data['created_time'] = strftime('%m/%d/%Y', $data['created_time']);
                }
                $intCnt = intval($objReviewsTable->getReviewListCntWithUID($this->_tplvar['user']['id']));
                $intPageSize = UserController::REVIEW_PAGE_SIZE;
                break;
            }
            default: {
                $arrResult['status'] = -1;
            }
        }
        if ($arrResult['status'] == -1) {
            $arrResult['content'] = 'param error.';
            echo json_encode($arrResult);
            return;
        }
        
        $intPageCnt = intval($intCnt / $intPageSize);
        if ($intCnt % $intPageSize != 0) {
            $intPageCnt += 1;
        }
        $arrPageList = Utils::genPageList($intPageCnt, $intCurPage);
        $arrResult['data_list'] = $arrDataList;
        $arrResult['page_list'] = $arrPageList;
        $arrResult['pre_page'] = $intCurPage == 1 ? $intCurPage : $intCurPage -1;
        $arrResult['next_page'] = $intCurPage == $intPageCnt ? $intPageCnt : $intPageCnt + 1;
        //var_dump($arrResult);
        echo json_encode($arrResult);
    }
    public function ajaxuploadfileAction()
    {
        $this->_ajaxCheckLogin();
        $GLOBALS['g_logger']->info('upload file: name'. $_FILES['photo']['name']);
        $arrResult = array();
        $arrResult['status'] = 0;
        $arrResult['content'] = 'success';
        $strOrgTargetPath = '';
        $objImage = new Image();
        $bRet = $objImage->upload_image($_FILES['photo'], $strOrgTargetPath);
        if ($bRet === false) {
            $arrResult['content'] = $objImage->error_msg;
            $arrResult['status'] = -1;
            echo json_encode($arrResult);
            return;
        }
        //TODO:update user info 
        
        //生成缩略图
        $strThumbTargetPath = '';
        $bRet = $objImage->make_thumb($strOrgTargetPath, UserController::THUMB_WIDTH, UserController::THUMB_HEIGHT, $strThumbTargetPath);
        if ($bRet === false) {
            $arrResult['content'] = $objImage->error_msg;
            $arrResult['status'] = -1;
            echo json_encode($arrResult);
            return;
        }
        else{
            $arrResult['content'] = FITWOW_WEB_SITE . '/' . $strThumbTargetPath;
        }
        $objUsersTable = new UsersTable();
        $arrUpdateInfo = array('org_photo' => $strOrgTargetPath, 'thumb_photo' => $strThumbTargetPath);
        $objUsersTable->updateUserWithID($this->_tplvar['user']['id'], $arrUpdateInfo);
        echo json_encode($arrResult);
    }
    
    //delete user photo
    public function deletephotoAction()
    {
        $this->_ajaxCheckLogin();
        $objUsersTable = new UsersTable();
        $objUser = $objUsersTable->findUserWithID($this->_tplvar['user']['id']);
        @unlink($objUser->thumb_photo);
        $objUser->thumb_photo = UserController::THUMB_DEFAULT_PATH;
        $objUser->save();
        $arrResult = array('status' => 0, 'content' => '/' . UserController::THUMB_DEFAULT_PATH);
        echo json_encode($arrResult);
    }
    
    //upload fd friends list
    public function ajaxuploadfbfriendlistAction()
    {
        $arrFbFriendsInfo = $this->_request->getParam('fb_friends_info');
        $arrFbFriendsInfo = $arrFbFriendsInfo['data'];
        $arrFirstThreeFriends = array();
        $idx = 0;
        foreach ($arrFbFriendsInfo as &$friend) {
            $friend['is_invited'] = 0;
            if ($idx < 3) {
                $arrFirstThreeFriends[$idx++] = $friend;
            }
        }
        $strFbJsonInfo = json_encode($arrFbFriendsInfo);
        
        $arrUserData = array(
            'fb_json_friends' => $strFbJsonInfo,
            
        );
        $objUsersTable = new UsersTable();
        $objUsersTable->updateUserWithID($this->_tplvar['user']['id'], $arrUserData);
        $arrResult = array('status' => 0, 'content' => $arrFirstThreeFriends);
        
        echo json_encode($arrResult);
    }
        
    //invite fb friends 
    public function ajaxinvitefbfriendAction()
    {
        $this->_ajaxCheckLogin();
        $strFbUID = $this->_request->getParam('fb_uid');
        $arrFbFriendList = json_decode($this->_tplvar['user']['fb_json_friends']);
        foreach ($arrFbFriendList as &$friend) {
            if ($friend->id == $strFbUID) {
                $friend->is_invited = 1;
            }
        }
        $arrUserData = array(
            'fb_json_friends' => json_encode($arrFbFriendList),
            
        );
        $objUsersTable = new UsersTable();
        $objUsersTable->updateUserWithID($this->_tplvar['user']['id'], $arrUserData);
        
        $arrResult = array('status' => 0, 'content' => 'success');      
        echo json_encode($arrResult);
    }    
    
    public function ajaxskipfbfriendAction()
    {
        $this->_ajaxCheckLogin();
        $arrFriend = $this->_selectRandomFriend();
        $arrResult = array('status' => 0, 'content' => $arrFriend);
        echo json_encode($arrResult);
    }

    protected function _selectRandomFriend()
    {
        $arrNotInvitedFriendList = array();
        $arrFbFriendList = json_decode($this->_tplvar['user']['fb_json_friends']);
        foreach ($arrFbFriendList as $friend) {
            if ($friend->is_invited == 0) {
                $arrNotInvitedFriendList[] = array('name' => $friend->name, 'id' => $friend->id);
            }
        }
        $cnt = count($arrNotInvitedFriendList);
        $idx = rand(0, $cnt-1);
        return $arrNotInvitedFriendList[$idx];
    }

    
    public function doaccountAction()
    {   
        //TODO:check user login
        $this->_ajaxCheckLogin();
        $strEmail = $this->_request->getParam('email');
        $strPassword = $this->_request->getParam('password');
        $strRepassword = $this->_request->getParam('repassword');
        $arrResult = array('status' => 0, 'content' => '');
        if (Utils::checkEmail($strEmail) === false) {
            $arrResult['status'] = -1;
            $arrResult['content'] = $GLOBALS['_LANG']['email_invalid'];
            echo json_encode($arrResult);
            return ;
        }
        else {
            $objUsersTable = new UsersTable();
            //TODO: 判断是否和当前的email是否相同
            $row = $objUsersTable->findUserWithEmail($strEmail);
            if ($row != null) {
                if ($row->email != $this->_tplvar['user']['email']) {
                    $arrResult['status'] = -1;
                    $arrResult['content'] = $GLOBALS['_LANG']['email_exist'];
                    echo json_encode($arrResult);
                    return;
                }
            }
            if (strlen($strPassword) < 6 || strlen($strRepassword) < 6) {
                $arrResult['status'] = -1;
                $arrResult['content'] = $GLOBALS['_LANG']['password_short'];
                echo json_encode($arrResult);
                return;
            }
            if ($strPassword != $strRepassword) {
                $arrResult['status'] = -1;
                $arrResult['content'] = $GLOBALS['_LANG']['password_not_equal'];
                echo json_encode($arrResult);
                return;
            }
            //update user account
            $arrData = array(
                'email' => $strEmail,
                'password'  => md5($strPassword),
            );
            
            $objUsersTable->updateUserWithID($this->_tplvar['user']['id'], $arrData);
        
            $arrResult = array('status' => 0, 'content' => 'update success.');
            echo json_encode($arrResult);
        }
    }
    
    public function dobasicAction()
    {
        //TODO: check user login
        $this->_ajaxCheckLogin();
        $strFirstname = $this->_request->getParam('firstname');
        $strLastname  = $this->_request->getParam('lastname');
        $strPaypalEmail = $this->_request->getParam('paypal_email');
        $intGender = intval($this->_request->getParam('gender'));
        $intArea   = intval($this->_request->getParam('area'));
        //TODO: check the input
        if (empty($strPaypalEmail) == false && Utils::checkEmail($strPaypalEmail) === false) {
            $arrResult['status'] = -1;
            $arrResult['content'] = $GLOBALS['_LANG']['email_invalid'];
            echo json_encode($arrResult);
            return ;
        }
        $arrData = array(
            'firstname' => htmlspecialchars($strFirstname),
            'lastname'  => htmlspecialchars($strLastname),
            'paypal_email' => $strPaypalEmail,
            'gender'       => $intGender,
            'area_id'         => $intArea
        );

        $objUsersTable = new UsersTable();
        $objUsersTable->updateUserWithID($this->_tplvar['user']['id'], $arrData);
        
        $arrResult = array('status' => 0, 'content' => 'update success.');
        echo json_encode($arrResult);
    }
    
    public function doclientprofileAction()
    {
        //TODO: check user login
        $this->_ajaxCheckLogin();
        $strGenGoals = $this->_request->getParam('gen_goals');
        $strInterestedActivities = $this->_request->getParam('interested_activities');
        $intAgeId = intval($this->_request->getParam('age_id'));
        $intBodyId = intval($this->_request->getParam('body_id'));
        //TODO: check the input
        $arrData = array(
            'gen_goals' => $strGenGoals,
            'interested_activities' => $strInterestedActivities,
            'age_id' => $intAgeId,
            'body_id' => $intBodyId
        );
        $objUsersTable = new UsersTable();
        $objUsersTable->updateUserWithID($this->_tplvar['user']['id'], $arrData);
        
        $arrResult = array('status' => 0, 'content' => 'update success.');
        echo json_encode($arrResult);
    }
    
    public function dotrainerprofileAction()
    {
        //TODO: check user login
        $this->_ajaxCheckLogin();
        $strCredentials = $this->_request->getParam('credentials');
        $strInterestedActivities = $this->_request->getParam('interested_activities');
        $intTrainingserviceId = intval($this->_request->getParam('trainingservice_id'));
        $intExperienceId = intval($this->_request->getParam('experience_id'));
        $intEdulevelId = intval($this->_request->getParam('edulevel_id'));
        $strSchool = $this->_request->getParam('school');
        $strMajor  = $this->_request->getParam('major');
        $strBIO = $this->_request->getParam('bio');
        $intAgeId = intval($this->_request->getParam('age_id'));
        $intBodyId = intval($this->_request->getParam('body_id'));
        //TODO: check the input
        $arrData = array(
            'credentials' => $strCredentials,
            'interested_activities' => $strInterestedActivities,
            'age_id' => $intAgeId,
            'body_id' => $intBodyId,
            'trainingservice_id' => $intTrainingserviceId,
            'experience_id' => $intExperienceId,
            'edulevel_id' => $intEdulevelId,
            'school' => htmlspecialchars($strSchool),
            'major' => htmlspecialchars($strMajor),
            'bio'   => htmlspecialchars($strBIO),
        );
        $objUsersTable = new UsersTable();
        $objUsersTable->updateUserWithID($this->_tplvar['user']['id'], $arrData);
        
        $arrResult = array('status' => 0, 'content' => 'update success.');
        echo json_encode($arrResult);
    }
    
    public function fbloginAction()
    {
        $arrFBUserInfo = $this->_request->getParam('fb_user_info');
        $intUserType = intval($this->_request->getParam('user_type'));
        //$intAreaId   = intval($this->_request->getParam('area_id'));
        $objUsersTable = new UsersTable();
        $objRow = $objUsersTable->getUserWithFBUID($arrFBUserInfo['id']);
        $bFirstLogin = false;
        if ($objRow == null) {
            //new user
            $intTime = time();

            $arrData = array(
                'fb_uid' => $arrFBUserInfo['id'],
                'firstname' => $arrFBUserInfo['first_name'],
                'lastname'  => $arrFBUserInfo['last_name'],
                'gender'  => $arrFBUserInfo['gender'] == 'male' ? 1 : 2,
                'fb_json_content' => json_encode($arrFBUserInfo),
                'reg_time' => $intTime,
                'last_login' => $intTime,
                'modified_time' => $intTime,
                'user_type' => $intUserType,
                'email' => $arrFBUserInfo['email'],
                'thumb_photo' => self::THUMB_DEFAULT_PATH,
            );
            $objUser = $objUsersTable->findUserWithEmail($arrFBUserInfo['email']);
            if ($objUser == null && !isset($_SESSION['user'])) {
                $objUsersTable->insert($arrData);
                $_SESSION['user'] = $objUsersTable->getUserWithFBUID($arrFBUserInfo['id'])->toArray();
                $bFirstLogin = true;
            }
            else if (isset($_SESSION['user'])){
                //user is logined and bind to facebook account
                $objUser = $objUsersTable->findUserWithID($_SESSION['user']['id']);
                if (empty($objUser->email)){
                    $objUser->email = $arrFBUserInfo['email'];
                }
                $objUser->fb_uid = $arrFBUserInfo['id'];
                $objUser->fb_json_content = json_encode($arrFBUserInfo);
                $objUser->modified_time = $intTime;
                $objUser->save();
                $_SESSION['user'] = $objUser->toArray();
            }
            else {
                //user is not logined
                $objUser->fb_uid = $arrFBUserInfo['id'];
                $objUser->fb_json_content = json_encode($arrFBUserInfo);
                $objUser->modified_time = $intTime;
                $objUser->save();
                $_SESSION['user'] = $objUser->toArray();
            }
        }
        else {
            $_SESSION['user'] = $objRow->toArray();
            // $objRow->user_type = $intUserType;
            // $objRow->save();
            // $arrData = array(
                // 'area_id' => $intAreaId,
            // );
            // $objUsersTable->updateUserWithID($_SESSION['user']['id'], $arrData);
        }
        
        $arrResult = array('status' => 0, 'content' => 'login success.');
        $arrResult['data'] = $_SESSION['user'];
        if (isset($_SESSION['goal'])) {
            //insert
            /* $objGoalModel = new GoalModel();
            $arrData = $_SESSION['goal'];
            $arrData['uid'] = $_SESSION['user']['id'];
            $intGID = $objGoalModel->insertNewGoal($arrData);
            $_SESSION['goal_id'] = $intGID; */
            unset($_SESSION['goal']);
            
            if ($_SESSION['user']['user_type'] == 1) {
                $arrResult['status'] = 3; // trainer can not post goal.
            }
            else {
                $arrResult['status'] = 1;
            }
        }
        if (isset($_SESSION['pre_url'])) {
            $arrResult['data']['has_pre_url'] = 1;
            $arrResult['data']['pre_url'] = $_SESSION['pre_url'];
            unset($_SESSION['pre_url']);
        }
        else {
            $arrResult['data']['has_pre_url'] = 0;
        }
        if ($bFirstLogin) {
            $arrResult['status'] = 2;
        }
        if (FITWOW_USE_FB_PIC) {
            $this->_storeFBPic($_SESSION['user']['fb_uid']);
        }
        echo json_encode($arrResult);
    }
    
    
    protected function _storeFBPic($strFBUID)
    {
        //get fb user picture
        $objUsersTable = new UsersTable();

        $objUser = $objUsersTable->getUserWithFBUID($strFBUID);
        if ($objUser->thumb_photo == self::THUMB_DEFAULT_PATH) {
            $strPicUrl = str_replace('{*$uid*}', $strFBUID, self::FB_PIC_URL);
            $strPicFilename = time().rand(0,10000).'.jpg'; 
            $strStorePicFilename = FITWOW_UPLOAD_PATH . $strPicFilename;
            $bRet = Utils::getFBPic($strPicUrl, $strStorePicFilename);
            if ($bRet === true) {
                $objUser->thumb_photo = 'image/head_picture/' . $strPicFilename;
                $objUser->save();
            }
        }
    }
    
    public function commonloginAction()
    {
        $strEmail = $this->_request->getParam('email');
        $strPassword = $this->_request->getParam('password');
        $arrResult = array('status' => 0, 'content' => 'login success.');
        if (empty($strEmail) || empty($strPassword)) {
            $arrResult['status'] = -1;
            $arrResult['content'] = 'email or password is empty.';
            echo json_encode($arrResult);
            return;
        }
        else {
            $objUsersTable = new UsersTable();
            $objRow = $objUsersTable->getUserWithEmailAndPassword($strEmail, md5($strPassword));
            if ($objRow == null) {
                $arrResult['status'] = -1;
                $arrResult['content'] = 'email or password is not right.';
                echo json_encode($arrResult);
                return;
            }
            else {
                $_SESSION['user'] = $objRow->toArray();
                $arrResult['data'] = $_SESSION['user'];
            }
        }
        
        if (isset($_SESSION['goal'])) {
            //insert
            /* $objGoalModel = new GoalModel();
            $arrData = $_SESSION['goal'];
            $arrData['uid'] = $_SESSION['user']['id'];
            $intGID = $objGoalModel->insertNewGoal($arrData);
            $_SESSION['goal_id'] = $intGID; */
            
            unset($_SESSION['goal']);
            if ($_SESSION['user']['user_type'] == 1) {
                $arrResult['status'] = 3; // trainer can not post goal.
            }
            else {
                $arrResult['status'] = 1;
            }
        }
        
        if (isset($_SESSION['pre_url'])) {
            $arrResult['data']['has_pre_url'] = 1;
            $arrResult['data']['pre_url'] = $_SESSION['pre_url'];
            unset($_SESSION['pre_url']);
        }
        else {
            $arrResult['data']['has_pre_url'] = 0;
        }
        echo json_encode($arrResult);
    }
    
    public function dojoinAction()
    {
        $strEmail = $this->_request->getParam('email');
        $strPassword = $this->_request->getParam('password');
        $strPaypalEmail = $this->_request->getParam('paypal_email');
        $strFirstname = $this->_request->getParam('firstname');
        $strLastname  = $this->_request->getParam('lastname');
        $intGender = $this->_request->getParam('gender');
        $intUserType = intval($this->_request->getParam('user_type'));
        $intAreaId   = intval($this->_request->getParam('area_id'));
        $arrResult = array('status' => 0, 'content' => 'Register success.');
        if ($intUserType == 0) {
            $intUserType = 2;
        }
        if (empty($strEmail) || empty($strPassword)) {
            $arrResult['status'] = -1;
            $arrResult['content'] = 'email or password is empty.';
            echo json_encode($arrResult);
            return;
        }
        if (empty($strFirstname) || empty($strLastname)) {
            $arrResult['status'] = -1;
            $arrResult['content'] = 'first or lastname is empty.';
            echo json_encode($arrResult);
            return;
        }

        
        $objUsersTable = new UsersTable();
        $objRow = $objUsersTable->findUserWithEmail($strEmail);
        if ($objRow != null) {
            $arrResult['status'] = -1;
            $arrResult['content'] = 'Email have already existed.';
            echo json_encode($arrResult);
            return;
        }
        $intTime = time();
        $arrData = array(
            'email' => $strEmail,
            'password' => md5($strPassword),
            'paypal_email' => $strPaypalEmail,
            'firstname' => htmlspecialchars($strFirstname),
            'lastname'  => htmlspecialchars($strLastname),
            'gender'    => $intGender,
            'reg_time' => $intTime,
            'last_login' => $intTime,
            'modified_time' => $intTime,
            'user_type' => $intUserType,
            'area_id' => $intAreaId,
            'thumb_photo' => self::THUMB_DEFAULT_PATH,
            

        );
        $intUID = $objUsersTable->insert($arrData);
        $arrData['id'] = $intUID;
        $_SESSION['user'] = $arrData;
        $arrResult['data'] = $arrData;
        if (isset($_SESSION['goal'])) {
            //insert
            /* $objGoalModel = new GoalModel();
            $arrData = $_SESSION['goal'];
            $arrData['uid'] = $_SESSION['user']['id'];
            $intGID = $objGoalModel->insertNewGoal($arrData);
            $_SESSION['goal_id'] = $intGID; */
            unset($_SESSION['goal']);
            if ($_SESSION['user']['user_type'] == 1) {
                $arrResult['status'] = 3; // trainer can not post goal.
            }
            else {
                $arrResult['status'] = 1;
            }
        }
        
        if (isset($_SESSION['pre_url'])) {
            $arrResult['data']['has_pre_url'] = 1;
            $arrResult['data']['pre_url'] = $_SESSION['pre_url'];
            unset($_SESSION['pre_url']);
        }
        else {
            $arrResult['data']['has_pre_url'] = 0;
        }
        echo json_encode($arrResult);
    }
    
    
    public function logoutAction()
    {
        unset($_SESSION['user']);
        $response = $this->getResponse();
        $response->setRedirect('/goal/search');
    }
    
    public function forgetpwdAction()
    {
        $strEmail = $this->_request->getParam('email');
        $objUsersTable = new UsersTable();
        $objUser = $objUsersTable->findUserWithEmail($strEmail);
        $arrResult = array('status' => 0);
        if ($objUser == null) {
            $arrResult['status'] = -1;
            $arrResult['content'] = 'Email do not exist.';
            echo json_encode($arrResult);
            return;
        }
        $strCode = md5(md5($strEmail.time()));
        $arrData = array(
            'email' => $strEmail,
            'code'  => $strCode,
            'status' => 0,
            'created_time' => time(),
        );
        $objResetPwdsTable = new ResetPwdsTable();
        $intRID = $objResetPwdsTable->insert($arrData);
        if ($intRID <= 0) {
            $arrResult['status'] = -1;
            $arrResult['content'] = 'Insert Failed.';
        }
        
        $objNoticeModel = new NoticeModel();
        $arrData = array(
            'client_firstname' => $objUser->firstname,
            'password_url'     => FITWOW_WEB_SITE . '/user/resetpwd?code='.$strCode, 
        );
        $objNoticeModel->insertNewEmail(7, array($strEmail), $arrData);
        echo json_encode($arrResult);
    }
    
    public function resetpwdAction()
    {
        $strCode = $this->_request->getParam('code'); 
        if (empty($strCode)){
            echo "param is not valid.";
            return;
        }
        $objResetPwdsTable = new ResetPwdsTable();
        $objResetPwd = $objResetPwdsTable->getResetPwdWithCode($strCode);
        if ($objResetPwd == null) {
            echo "param is not valid.";
            return;
        }
        //ok
        $objResetPwd->status = 1;
        $objResetPwd->save();
        $objUsersTable = new UsersTable();
        $objUser = $objUsersTable->findUserWithEmail($objResetPwd->email);
        if ($objUser == null) {
            echo "param is not valid.";
            return;
        }
        $_SESSION['user'] = $objUser->toArray();
        $response = $this->getResponse();
        $response->setRedirect('/user/account');
    }
    
    protected function _checkUserLogin()
    {
        if (!isset($_SESSION['user'])) {
            $response = $this->getResponse();
            $response->setRedirect('/user/login');
            //exit(0);
        }
    }
    
    protected function _ajaxCheckLogin()
    {
        if (!isset($_SESSION['user'])) {
            $arrResult = array('status' => -1, 'content' => 'You are not logined. Please login');
            echo json_encode($arrResult);
            exit(0);
        }
    }
    
    protected function _genRevewAndBidPageList()
    {
        $objReviewsTable = new ReviewsTable();
        $objBidsTable = new BidsTable();
        $intCnt = intval($objReviewsTable->getReviewListCntWithUID($this->_tplvar['user']['id']));
        $intPageCnt = intval($intCnt / UserController::REVIEW_PAGE_SIZE);
        if ($intCnt % UserController::REVIEW_PAGE_SIZE != 0) {
            $intPageCnt += 1;
        }
        $this->_tplvar['review_page_list'] = Utils::genPageList($intPageCnt, 1);
        $this->_tplvar['review_page_cnt'] = $intPageCnt;
        $intCnt = intval($objBidsTable->getBidListCntWithUID($this->_tplvar['user']['id']));
        $intPageCnt = intval($intCnt / UserController::BID_PAGE_SIZE);
        if ($intCnt % UserController::BID_PAGE_SIZE != 0) {
            $intPageCnt += 1;
        }
        $this->_tplvar['bid_page_list'] = Utils::genPageList($intPageCnt, 1);
        $this->_tplvar['bid_page_cnt']  = $intPageCnt;
    }
    protected function _genMyGoalsAndFriendGoalsPageList()
    {
        $objGoalsTable = new GoalsTable();
        $arrWhere = array(
            'uid='.$this->_tplvar['user']['id'],
        );
        $intMyGoalCnt = intval($objGoalsTable->getProjectCnt($arrWhere));
        $intCurPage= 1;
        $intPageCnt = intval($intMyGoalCnt / UserController::GOAL_PAGE_SIZE);
        if ($intMyGoalCnt % UserController::GOAL_PAGE_SIZE != 0) {
            $intPageCnt += 1;
        }
        $this->_tplvar['my_goal_page_list'] = Utils::genPageList($intPageCnt, $intCurPage);
        $this->_tplvar['my_goal_page_cnt']  = $intPageCnt;
        $intFriendsGoalCnt = $objGoalsTable->getFriendsGoalListCntWithUID($this->_tplvar['user']['id']);
        $intPageCnt = intval($intFriendsGoalCnt / UserController::GOAL_PAGE_SIZE);
        if ($intFriendsGoalCnt % UserController::GOAL_PAGE_SIZE != 0) {
            $intPageCnt += 1;
        }
        $this->_tplvar['friends_page_list'] = Utils::genPageList($intPageCnt, 1);
        $this->_tplvar['friends_page_cnt'] = $intPageCnt;
    }
    
    protected function _calcProfileComplete($intUID) 
    {
        $objUsersTable = new UsersTable();
        $objUser = $objUsersTable->findUserWithID($intUID);
        if ($objUser == null) {
            return false;
        }
        
        $intComplete = 1;
        $intCnt = 2;
        if (!empty($objUser->area_id)) {
            $intComplete = 1;
        }
        if ($objUser->thumb_photo != UserController::THUMB_DEFAULT_PATH) {
            $intComplete = 1;
        }
        if ($objUser->user_type == 1) {
            //$intCnt += 2;
            if (!empty($objUser->experience_id)) {
                $intComplete += 1;
            }
        }
        else {
            //$intCnt += 6;
            if (!empty($objUser->gen_goals)) {
                $intComplete += 1;
            }
        }
        $intRes = intval($intComplete*100 / $intCnt);
        return $intRes;
    }
    protected $_tplvar;
} 

 ?>